package jnpf.zcasset.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jnpf.model.visiual.superQuery.ConditionJsonModel;
import jnpf.model.visiual.superQuery.SuperQueryConditionModel;
import jnpf.model.visiual.superQuery.SuperQueryJsonModel;
import jnpf.permission.model.authorize.AuthorizeConditionModel;
import jnpf.permission.service.AuthorizeService;
import jnpf.util.*;
import jnpf.zcasset.entity.ZcAssetMortgageEntity;
import jnpf.zcasset.mapper.ZcAssetMortgageMapper;
import jnpf.zcasset.model.zcassetmortgage.ZcAssetMortgageForm;
import jnpf.zcasset.model.zcassetmortgage.ZcAssetMortgagePagination;
import jnpf.zcasset.service.ZcAssetMortgageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 *
 * 资产抵押
 * 版本： V3.2.0
 * 版权： 智果云科技（https://www.jnpfsoft.com）
 * 作者： JNPF开发平台组
 * 日期：
 */
@Service
public class ZcAssetMortgageServiceImpl extends ServiceImpl<ZcAssetMortgageMapper, ZcAssetMortgageEntity> implements ZcAssetMortgageService {


        @Autowired
        private GeneraterSwapUtil generaterSwapUtil;

        @Autowired
        private UserProvider userProvider;

        @Autowired
        private AuthorizeService authorizeService;





    @Override
    public List<ZcAssetMortgageEntity> getList(ZcAssetMortgagePagination zcAssetMortgagePagination){
        return getTypeList(zcAssetMortgagePagination,zcAssetMortgagePagination.getDataType());
    }
    @Override
    public List<ZcAssetMortgageEntity> getTypeList(ZcAssetMortgagePagination zcAssetMortgagePagination,String dataType){
        String userId=userProvider.get().getUserId();
        List<String> AllIdList =new ArrayList();
		List<List<String>> intersectionList =new ArrayList<>();
		int total=0;
		int zcAssetMortgageNum =0;
        QueryWrapper<ZcAssetMortgageEntity> zcAssetMortgageQueryWrapper=new QueryWrapper<>();
		List<String> allSuperIDlist = new ArrayList<>();
		String superOp ="";
	if (ObjectUtil.isNotEmpty(zcAssetMortgagePagination.getSuperQueryJson())){
		SuperQueryJsonModel superQueryJsonModel = JsonUtil.getJsonToBean(zcAssetMortgagePagination.getSuperQueryJson(), SuperQueryJsonModel.class);
		String matchLogic = superQueryJsonModel.getMatchLogic();
		List<ConditionJsonModel> superQueryList = JsonUtil.getJsonToList(superQueryJsonModel.getConditionJson(), ConditionJsonModel.class);
		for (ConditionJsonModel conditionjson : superQueryList){
            Map<String, Object> map = JsonUtil.stringToMap(conditionjson.getAttr());
            Map<String, Object> configMap = JsonUtil.stringToMap(map.get("__config__").toString());
            String tableName = configMap.get("relationTable")!=null ? String.valueOf(configMap.get("relationTable")) : String.valueOf(configMap.get("tableName"));
		    if (map.get("multiple") != null) {
		        if (Boolean.valueOf(String.valueOf(map.get("multiple"))) && ObjectUtil.isNull(conditionjson.getFieldValue())) {
		            conditionjson.setFieldValue("[]");
		        }
		    }
            conditionjson.setTableName(tableName);
		}
		List<String> allSuperList = new ArrayList<>();
		List<List<String>> intersectionSuperList  = new ArrayList<>();
        int zcAssetMortgageNum1 = 0;
        QueryWrapper<ZcAssetMortgageEntity> zcAssetMortgageSuperWrapper = new QueryWrapper<>();
        zcAssetMortgageNum1 = generaterSwapUtil.getCondition(new SuperQueryConditionModel(zcAssetMortgageSuperWrapper,superQueryList,matchLogic,"zcAssetMortgage")
        ,new ZcAssetMortgageEntity(),zcAssetMortgageNum1);
            if (zcAssetMortgageNum1>0){
            List<String> zcAssetMortgageList =this.list(zcAssetMortgageSuperWrapper).stream().map(ZcAssetMortgageEntity::getId).collect(Collectors.toList());
            allSuperList.addAll(zcAssetMortgageList);
            intersectionSuperList.add(zcAssetMortgageList);
            }
		superOp = matchLogic;
		//and or
		if(matchLogic.equalsIgnoreCase("and")){
		    allSuperIDlist = generaterSwapUtil.getIntersection(intersectionSuperList);
		}else{
		    allSuperIDlist = allSuperList;
		}
    }
    boolean pcPermission = false;
    boolean appPermission = false;
    boolean	isPc = ServletUtil.getHeader("jnpf-origin").equals("pc");
    if(isPc && pcPermission){
		if (!userProvider.get().getIsAdministrator()){
				Object zcAssetMortgageObj=authorizeService.getCondition(new AuthorizeConditionModel(zcAssetMortgageQueryWrapper,zcAssetMortgagePagination.getMenuId(),"zc_asset_mortgage"));
            if (ObjectUtil.isEmpty(zcAssetMortgageObj)){
                return new ArrayList<>();
            } else {
                zcAssetMortgageQueryWrapper = (QueryWrapper<ZcAssetMortgageEntity>)zcAssetMortgageObj;
                zcAssetMortgageNum++;
            }
        }
    }
    if(!isPc && appPermission){
		if (!userProvider.get().getIsAdministrator()){
			Object zcAssetMortgageObj=authorizeService.getCondition(new AuthorizeConditionModel(zcAssetMortgageQueryWrapper,zcAssetMortgagePagination.getMenuId(),"zcAssetMortgage"));
            if (ObjectUtil.isEmpty(zcAssetMortgageObj)){
                return new ArrayList<>();
            } else {
            zcAssetMortgageQueryWrapper = (QueryWrapper<ZcAssetMortgageEntity>)zcAssetMortgageObj;
            zcAssetMortgageNum++;
			}


		}
    }
        if(isPc){
			if(ObjectUtil.isNotEmpty(zcAssetMortgagePagination.getAssetId())){
            zcAssetMortgageNum++;
                zcAssetMortgageQueryWrapper.lambda().eq(ZcAssetMortgageEntity::getAssetId,zcAssetMortgagePagination.getAssetId());
                    }

			if(ObjectUtil.isNotEmpty(zcAssetMortgagePagination.getMortgageCompany())){
            zcAssetMortgageNum++;
                zcAssetMortgageQueryWrapper.lambda().eq(ZcAssetMortgageEntity::getMortgageCompany,zcAssetMortgagePagination.getMortgageCompany());
                    }

			if(ObjectUtil.isNotEmpty(zcAssetMortgagePagination.getMortgageStartDate())){
            zcAssetMortgageNum++;
            List MortgageStartDateList =  JsonUtil.getJsonToList(zcAssetMortgagePagination.getMortgageStartDate(),String.class);
                    Long fir = Long.valueOf(String.valueOf(MortgageStartDateList.get(0)));
                    Long sec = Long.valueOf(String.valueOf(MortgageStartDateList.get(1)));

                zcAssetMortgageQueryWrapper.lambda().ge(ZcAssetMortgageEntity::getMortgageStartDate, new Date(fir))
            .le(ZcAssetMortgageEntity::getMortgageStartDate, DateUtil.stringToDate(DateUtil.daFormatYmd(sec) + " 23:59:59"));

                    }

			if(ObjectUtil.isNotEmpty(zcAssetMortgagePagination.getMortgageEndDate())){
            zcAssetMortgageNum++;
            List MortgageEndDateList =  JsonUtil.getJsonToList(zcAssetMortgagePagination.getMortgageEndDate(),String.class);
                    Long fir = Long.valueOf(String.valueOf(MortgageEndDateList.get(0)));
                    Long sec = Long.valueOf(String.valueOf(MortgageEndDateList.get(1)));

                zcAssetMortgageQueryWrapper.lambda().ge(ZcAssetMortgageEntity::getMortgageEndDate, new Date(fir))
            .le(ZcAssetMortgageEntity::getMortgageEndDate, DateUtil.stringToDate(DateUtil.daFormatYmd(sec) + " 23:59:59"));

                    }

			if(ObjectUtil.isNotEmpty(zcAssetMortgagePagination.getMortgageAmount())){
            zcAssetMortgageNum++;
            zcAssetMortgageQueryWrapper.lambda().like(ZcAssetMortgageEntity::getMortgageAmount,zcAssetMortgagePagination.getMortgageAmount());
                    }

			if(ObjectUtil.isNotEmpty(zcAssetMortgagePagination.getRemark())){
            zcAssetMortgageNum++;
            zcAssetMortgageQueryWrapper.lambda().like(ZcAssetMortgageEntity::getRemark,zcAssetMortgagePagination.getRemark());
                    }

        }
		List<String> intersection = generaterSwapUtil.getIntersection(intersectionList);
		if (total>0){
		if (intersection.size()==0){
		    intersection.add("jnpfNullList");
		}
         zcAssetMortgageQueryWrapper.lambda().in(ZcAssetMortgageEntity::getId, intersection);
		}
        //是否有高级查询
		if (StringUtil.isNotEmpty(superOp)){
		    if (allSuperIDlist.size()==0){
		        allSuperIDlist.add("jnpfNullList");
		    }
		List<String> finalAllSuperIDlist = allSuperIDlist;
            zcAssetMortgageQueryWrapper.lambda().and(t->t.in(ZcAssetMortgageEntity::getId, finalAllSuperIDlist));
		}

        //排序
        if(StringUtil.isEmpty(zcAssetMortgagePagination.getSidx())){
        zcAssetMortgageQueryWrapper.lambda().orderByDesc(ZcAssetMortgageEntity::getId);
        }else{
            try {
            	String sidx = zcAssetMortgagePagination.getSidx();
                ZcAssetMortgageEntity zcAssetMortgageEntity = new ZcAssetMortgageEntity();
				Field declaredField = zcAssetMortgageEntity.getClass().getDeclaredField(sidx);
				declaredField.setAccessible(true);
				String value = declaredField.getAnnotation(TableField.class).value();
                 zcAssetMortgageQueryWrapper="asc".equals(zcAssetMortgagePagination.getSort().toLowerCase())?zcAssetMortgageQueryWrapper.orderByAsc(value):zcAssetMortgageQueryWrapper.orderByDesc(value);
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            }
        }
        if("0".equals(dataType)){
            if((total>0 && AllIdList.size()>0) || total==0){
                Page<ZcAssetMortgageEntity> page=new Page<>(zcAssetMortgagePagination.getCurrentPage(), zcAssetMortgagePagination.getPageSize());
                IPage<ZcAssetMortgageEntity> userIPage=this.page(page, zcAssetMortgageQueryWrapper);
                return zcAssetMortgagePagination.setData(userIPage.getRecords(),userIPage.getTotal());
            }else{
                List<ZcAssetMortgageEntity> list = new ArrayList();
                return zcAssetMortgagePagination.setData(list, list.size());
            }
        }else{
            return this.list(zcAssetMortgageQueryWrapper);
        }
    }


    @Override
    public ZcAssetMortgageEntity getInfo(String id){
        QueryWrapper<ZcAssetMortgageEntity> queryWrapper=new QueryWrapper<>();
        queryWrapper.lambda().eq(ZcAssetMortgageEntity::getId,id);
        return this.getOne(queryWrapper);
    }

    @Override
    public void create(ZcAssetMortgageEntity entity){
        this.save(entity);
    }

    @Override
    public boolean update(String id, ZcAssetMortgageEntity entity){
        return this.updateById(entity);
    }
    @Override
    public void delete(ZcAssetMortgageEntity entity){
        if(entity!=null){
            this.removeById(entity.getId());
        }
    }
    //子表方法

    //列表子表数据方法



    //验证表单唯一字段
    @Override
    public boolean checkForm(ZcAssetMortgageForm form, int i) {
        int total = 0;
		boolean isUp =StringUtil.isNotEmpty(form.getId()) && !form.getId().equals("0");
		String id="";
		if (isUp){
			 id = form.getId();
		}
        if (total>0){
        return true;
        }
        return false ;
    }


}
